package com.itheima.controller;

import com.itheima.entity.Dept;
import com.itheima.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;

@RestController
public class DeptController {
//    private static final Logger logger = LoggerFactory.getLogger(DeptController.class);
//
//    @RequestMapping("/depts")
//    public List<Dept> getAll() {
//        try {
//            // 1. 加载并读取 dept.txt 文件
//            URL url = this.getClass().getResource("/dept.txt");
//            if (url != null) {
//                logger.info("dept.txt file path: {}", url.getPath());
//            } else {
//                logger.error("dept.txt file not found in classpath");
//                throw new FileNotFoundException("dept.txt file not found in classpath");
//            }
//
//            InputStream input = this.getClass().getResourceAsStream("/dept.txt");//一定要加斜杠，才能编译成功
//            if (input == null) {
//                logger.error("dept.txt file not found in classpath");
//                throw new FileNotFoundException("dept.txt file not found in classpath");
//            }
//
//            List<String> strings = IOUtils.readLines(input, StandardCharsets.UTF_8);
//
//            // 2. 解析 dept.txt 文件，并封装成集合
//            List<Dept> depts = strings.stream().map((str) -> {
//                String[] part = str.split(",");
//                if (part.length != 3) {
//                    logger.error("Invalid line format: {}", str);
//                    throw new IllegalArgumentException("Invalid line format: " + str);
//                }
//                Integer deptId = Integer.valueOf(part[0]);
//                String name = part[1];
//                LocalDateTime updateTime = LocalDateTime.parse(part[2], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//                return new Dept(deptId, name, updateTime);
//            }).collect(Collectors.toList());
//
//            // 3. 返回部门信息（json格式）
//            return depts;
//        } catch (IOException e) {
//            logger.error("Failed to read dept.txt file", e);
//            throw new RuntimeException("Failed to read dept.txt file", e);
//        } catch (Exception e) {
//            logger.error("Failed to load department data", e);
//            throw new RuntimeException("Failed to load department data", e);
//        }
//    }

    private static final Logger logger = LoggerFactory.getLogger(DeptController.class);

    //@RequestMapping(value = "/depts",method = RequestMethod.GET)//与下行代码的效果相同
    @GetMapping("/depts")
    public Result getAll() {
        try {
            // 1. 加载并读取 dept.txt 文件
            URL url = this.getClass().getResource("/dept.txt");
            if (url != null) {
                logger.info("dept.txt file path: {}", url.getPath());
            } else {
                logger.error("dept.txt file not found in classpath");
                throw new FileNotFoundException("dept.txt file not found in classpath");
            }

            InputStream input = this.getClass().getResourceAsStream("/dept.txt");//一定要加斜杠，才能编译成功
            if (input == null) {
                logger.error("dept.txt file not found in classpath");
                throw new FileNotFoundException("dept.txt file not found in classpath");
            }

            List<String> strings = IOUtils.readLines(input, StandardCharsets.UTF_8);

            // 2. 解析 dept.txt 文件，并封装成集合
            List<Dept> depts = strings.stream().map((str) -> {
                String[] part = str.split(",");
                if (part.length != 3) {
                    logger.error("Invalid line format: {}", str);
                    throw new IllegalArgumentException("Invalid line format: " + str);
                }
                Integer deptId = Integer.valueOf(part[0]);
                String name = part[1];
                LocalDateTime updateTime = LocalDateTime.parse(part[2], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                return new Dept(deptId, name, updateTime);
            }).collect(Collectors.toList());

            // 3. 返回部门信息（json格式）
            return Result.success(depts);
        } catch (IOException e) {
            logger.error("Failed to read dept.txt file", e);
            throw new RuntimeException("Failed to read dept.txt file", e);
        } catch (Exception e) {
            logger.error("Failed to load department data", e);
            throw new RuntimeException("Failed to load department data", e);
        }
    }
}